const {$Toast} = require('../../../utils/iview/base/index');
const Tools = require('../../../utils/modules/Tools');
import NetWork from '../../../utils/modules/NetWork';

const app = getApp();

var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({
  data: {
    auth: true,
    isloade: {
      hidden: false
    },
    _baseUrl: app.globalData._baseUrl,
    _imgPath: app.globalData._imgPath,
    _imgPaths: app.globalData._imgPaths,
    _backImg: app.globalData._backImg,
    img: [],
    order_id: 0,
    user_type: 1,
    designer_id: '',
    openid: app.globalData.openid,
    key: app.globalData._key,
    shopName: '',
    shopId: '',
    userInfo: '',
    user: {},
  },

  onLoad: function (e) {
    this.setData({
      order_id: e.id
    })
    // console.log(this.data.data.order_id,"idid")

    this.addpage()
    // this.palys()
  },

  // onLoad(options) {
  //   var _that = this
  //   _that.setTitle('服务中');
  //   var user = wx.getStorageSync('user');
  //   var userInfo = wx.getStorageSync('userInfo');
  //   var { user } = _that.data;
  //   _that.setData({
  //     user: user,
  //     userInfo: userInfo,

  //   });

  // },


  onShow: function () {
    var _that = this
    var user = wx.getStorageSync('user');
    var userInfo = wx.getStorageSync('userInfo');

    // _that.setData({
    //   user: user ? user : '',
    //   openid: userInfo.openid ? userInfo.openid : '',
    //   userInfo: userInfo
    // })
    // _that.isUserInfo();

  },

  scanCode: function () {
    var that = this;
    wx.scanCode({ //扫描API
      success(res) { //扫描成功
        console.log(res) //输出回调信息
        that.setData({
          scanCodeMsg: res.result
        });
        wx.showToast({
          title: '成功',
          duration: 1000
        })
      }
    })
  },

  evaluate(e) {
    var { id, store_id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '../../evaluate/evaluate?id=' + id + '&store_id=' + store_id,
    })
  },


  //订单详情
  addpage() {
    let _that = this;
    var token = wx.getStorageSync('token');
    if (!token) {
      return;
    }

    let net = new NetWork(_that.data._baseUrl)
    net._request({
      url: 'api/v1/order/myOrderInfo',
      data: {
        token: token,
        order_id: _that.data.order_id
      },
      method: 'POST'
    }, '', res => {

      _that.setData({
        order: res.data.data
      })
      console.log(res.data.data, "输出")
      // console.log(_that.data.vehicle,"vehicle")     
    }, res => {
      if (res.data.error_code == 400 && res.data.msg == 'token无效或已过期') {
        app.refreshtoken(token);
        setTimeout(() => {
          _that.addpage();
        }, 1500)
      }
    });
  },


  //一键开箱
  num() {
    let _that = this;
    var token = wx.getStorageSync('token');
    if (!token) {
      return;
    }
    
    let net = new NetWork(_that.data._baseUrl)
    net._request({
      url: 'api/v1/order/opDoor',
      data: {
        token: token,
        order_id: _that.data.order_id
      },
      method: 'POST'
    }, '开柜', res => {
      if (res.data.error_code == 0){
        _that.addpage()
      }
      console.log(res.data.data, "输出一键开箱")
      // console.log(_that.data.vehicle,"vehicle")     
    }, res => {
      if (res.data.error_code == 400 && res.data.msg == 'token无效或已过期') {
        app.refreshtoken(token);
        setTimeout(() => {
          _that.num();
        }, 1500)
      }
      else if (res.data.error_code == 400) {
        $Toast({
          content: res.data.msg,
          type: 'warning'
        });
      }

    });
  },


  // 插队支付的弹框
  // ispay默认是flase,
  pays() {
    var _that = this;
    var ispay = _that.data.ispay;
    _that.setData({
      //！flase就是true,第一次
      ispay: !ispay
    })
  },


  palys1(e) {
    let _that = this;
    //这里是第二次调用 ispay变成了true,那么！ispay:!true 就变成了flase不显示
    _that.pays();
    wx.showModal({
      title: '提示',
      content: '确定要余额？',
      // 余额支付接口是和微信支付接口一样的，余额支付接口要在点击确定后在确认余额支付
      success(res) {
        if (res.confirm) {
          var token = wx.getStorageSync('token');
          var type = e.currentTarget.dataset.value;
          if (!token) {
            return;
          }

          let net = new NetWork(_that.data._baseUrl)
          net._request({
            url: 'api/v1/order/orderPay',
            data: {
              token: token,
              order_id: _that.data.order_id,
              jump_type: 1,
              pay_type: type
            },
            method: 'POST'
          }, '支付', res => {
            _that.addpage();


          }, res => {
            if (res.data.error_code == 400 && res.data.msg == 'token无效或已过期') {
              app.refreshtoken(token);
              setTimeout(() => {
                _that.num();
              }, 1500)
            }
            // else if (res.data.error_code == 0) {
            //   $Toast({
            //     content: res.data.msg,
            //   });


            // } 

            else if (res.data.error_code == 400) {
              $Toast({
                content: res.data.msg,
                type: 'warning'
              });
            }

          });
        }

        else if (res.cancel) {
        }
      }
    })
  },




  //支付接口
  palyss(e) {
    let _that = this;
    _that.pays();
    var token = wx.getStorageSync('token');
    let net = new NetWork(_that.data._baseUrl)
    var type = e.currentTarget.dataset.value;
    net._request({

      url: 'api/v1/order/orderPay',
      data: {
        token: token,
        order_id: _that.data.order_id,
        pay_type: type
      },
      method: 'POST'
    }, '', res => {

      console.log(res.data.data, "支付接口");
      var payment = res.data.data
      //只是支付接口，支付的功能的接口在那里就写在那个接口的res中
      //这个部分是按了确定才出现支付的， 所以写在这里
      wx.requestPayment({
        timeStamp: payment.timeStamp,
        nonceStr: payment.nonceStr,
        package: payment.packages,
        signType: payment.signType,
        paySign: payment.paySign,
        success(res) { 
          wx.showModal({
            content: '支付成功',
            showCancel:false,
            confirmColor:'#fe7e00',

            success: function (res) {
              if (res.confirm) {
                // 在支付完成这里调取订单详情接口就是刷新页面
                _that.addpage()
                // wx.redirectTo({
                //   url: '../orderList/orderDetails',
                // })
              }
              else if (res.cancel) {
                console.log('支付失败，请重新支付')
              }
            }

          })

          // setTimeout(() => {
          //   wx.navigateTo({
          //     url: '../orderList/orderDetails'
          //   })
          // }, 1500)


        },
        
        fail(res) { 
         
        }
      })
    }, res => {
      var data = res.data;
      if (data.error_code == 400 && data.msg == 'token无效或已过期') {
        app.refreshtoken(token);
        setTimeout(() => {
          _that.palyss();
        }, 1500)
      } else if (data.error_code == 400){
        $Toast({
          content: data.msg,
          type: 'warning'
        });
      }
    });
  },


  intoMap: function (e) {

    var address = e.currentTarget.dataset.value;
    console.log(address)
    var _this = this;
    //调用地址解析接口
    var qqmapsdk = new QQMapWX({
      key: _this.data.key // 必填
    });
    qqmapsdk.geocoder({
      //获取表单传入地址
      address: address, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function (res) {//成功后的回调
        var res = res.result;
        var latitude = res.location.lat;
        var longitude = res.location.lng;


        wx.openLocation({        //所以这里会显示你当前的位置
          latitude: latitude,
          longitude: longitude,
          name: address,
          address: address,
          scale: 28
        })
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    })


  },

  

  // cancelbtn() {
  //   wx.showModal({
  //     title: '取消订单',
  //     content: '您确定取消订单吗？若已产生成本费用,则需进行支付！',
  //     success(res) {
  //       console.log(res);
  //       if (res.cancel) {
  //         that.cancel();
  //       }
  //       if (res.confirm) {
  //         $Toast({
  //           content: '支付成功!',
  //           type: 'none'
  //         })
  //       }
  //     },
  //   })
  // },



  /* 拨打电话 */
  // telPhone() {
  // 	var that = this;
  // 	wx.makePhoneCall({
  // 		phoneNumber: ''
  // 	}, res => {

  // 	});
  // },
  /* 修改头部标题 */
  setTitle(str) {
    wx.setNavigationBarTitle({
      title: str,
      success: function () {

      }
    })
  },
  setType(e) {
    var index = e.target.dataset.index;
    this.setData({
      roomType: index
    })
  },
  // onShareAppMessage(str) {
  // 	return {
  // 		title: str,
  // 		path: this.route
  // 	}
  // },
  isUserInfo() {
    var _that = this;
    wx.getSetting({
      success(res) {
        // console.log(res)
        if (!res.authSetting['scope.userInfo']) {
          _that.setData({
            auth: false
          })

        }
      }
    })
  },

 

  userInfo(e) {

    let _that = this;
    let _userInfo = e.detail.userInfo;
    console.log(_userInfo)
    wx.setStorageSync('_userInfo', _userInfo);
    let net = new NetWork(app.globalData._baseUrl);
    let _data = e.detail;


    if (_userInfo) {
      this.setData({
        auth: true,
      })
    }


    wx.login({
      success(res) {
        if (res.code) {
          console.log(res.code, "code");

          net._request({
            url: 'api/v1/login/mini',
            method: 'POST',
            data: {
              code: res.code,
              rawData: _data.rawData,
              signature: _data.signature,
              iv: _data.iv,
              encryptedData: _data.encryptedData
            },
          }, '', res => {
            app.globalData.user = _userInfo;
            var user = res.data.data;
            wx.setStorageSync('userInfo', user);

            _that.setData({
              userInfo: user
            })

            wx.setStorageSync('user', {
              user_type: 1
            });
            $Toast({
              content: res.data.msg,
              type: 'success'
            });

          }, res => {
            console.log("失败返回", res);
            app.globalData.user = _userInfo;
            var user = res.data.data;
            wx.setStorageSync('userInfo', user);
            $Toast({
              content: res.data.msg,
              type: 'success'
            });
          });
        }
      }
    })
  },


  /* 设计师 */
  editprofile(e) {
    //console.log(e);

    wx.navigateTo({
      url: '../designer/editprofile?id=' + e.currentTarget.dataset.id,
    })
  },

  info2() {
    let _that = this;

    let values = {
      userId: _that.data.openid
    };

    let net = new NetWork(this.data._baseUrl)
    net._request({
      url: '/api/users/design/center',
      data: values,
      method: 'POST'
    }, '', res => {
      let _data = res.data.data;
      //console.log(_data)
      _that.setData({
        userInfo: _data,
        designer_id: _data.id
      })
      wx.setStorageSync('designer_id', _data.id)
    });
  },
  /* 设计师 end */

  /* 门店 */
  info3() {
    let _that = this;
    let {
      shop_id
    } = wx.getStorageSync("user");

    let net = new NetWork(this.data._baseUrl)
    net._request({
      url: '/api/Shop/shopInfo',
      data: {
        id: shop_id
      },
      method: 'POST'
    }, '', res => {
      let _data = res.data.data[0];
      _that.setData({
        userInfo: _data,
        shopId: _data.id,
        shopName: _data.name
      })

    });

  },
})